﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace AssetLoad
{
    public class WeaponLoader : LoaderBase
    {
        //private Dictionary<string, int> counter = new Dictionary<string, int>();
        //private Dictionary<string, int> unloadCounter = new Dictionary<string, int>();
        public override string GetPrefix()
        {
            return @"weaponPrefab/";
        }

        public IEnumerator LoadWeapon(string resourceName, LoadComplete callback)
        {
#if !FIX_RESOURCE
            string abName = GetPrefix() + resourceName;
            abName = abName.ToLower();
            AssetBundleManager.Instance.LoadAssetBundle(abName);
            while (!AssetBundleManager.Instance.IsLoadedAssetBundle(abName))
            {
                yield return null;
            }
            GameObjectPoolManager.Instance.Regist(abName, resourceName);
            if (callback != null)
            {
                var obj = GameObjectPoolManager.Instance.Spawn(abName, resourceName);
                callback(obj);
            }
            //if (counter.ContainsKey(resourceName))
            //{
            //    counter[resourceName]++;
            //}
            //else
            //{
            //    counter[resourceName] = 1;
            //}
            //Debug.Log("<color=cyan> load weapon " + resourceName + " " + counter[resourceName] + "</color>");
#else
            ResourceManager.Instance.LoadResource(GetPrefix() + resourceName);
            GameObjectPoolManager.Instance.Regist(GetPrefix() + resourceName);
            yield return 0;
            if (callback != null)
            {
                var obj = GameObjectPoolManager.Instance.Spawn(GetPrefix() + resourceName);
                callback(obj);
            }
#endif
        }

        public void UnloadWeapon(GameObject obj, string resourceName)
        {
#if !FIX_RESOURCE
            GameObjectPoolManager.Instance.Unspawn(obj);
            string abName = GetPrefix() + resourceName;
            abName = abName.ToLower();
            GameObjectPoolManager.Instance.UnRegist(abName, resourceName);
            AssetBundleManager.Instance.UnloadAssetBundle(abName);

            //if (unloadCounter.ContainsKey(resourceName))
            //{
            //    unloadCounter[resourceName]++;
            //}
            //else
            //{
            //    unloadCounter[resourceName] = 1;
            //}
            //Debug.Log("<color=yellow> unload weapon " + resourceName + " " + unloadCounter[resourceName] + "</color>");
#else
            GameObjectPoolManager.Instance.Unspawn(obj);
            GameObjectPoolManager.Instance.UnRegist(GetPrefix() + resourceName);
            ResourceManager.Instance.UnloadResource(GetPrefix() + resourceName);
#endif
        }
    }
}
